package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.converter.UserConverterMapper;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.UserLoginRequest;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.dto.UserRegisterRequest;
import com.cskaoyan.user.dto.UserRegisterResponse;
import com.cskaoyan.user.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * @description:
 * @date: 2022/05/18 22:08
 * @author: beiji
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Autowired
    MailSender mailSender;

    @Autowired
    UserConverterMapper userConverterMapper;

    @Override
    public UserLoginResponse userLogin(UserLoginRequest userLoginRequest) {
        UserLoginResponse response = new UserLoginResponse();
        // 校验参数
        userLoginRequest.requestCheck();
        // 验证用户名
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username",userLoginRequest.getUserName());
        List<Member> members = memberMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(members)){
            response.setCode(UserRetCode.USERORPASSWORD_ERRROR.getCode());
            response.setMsg(UserRetCode.USERORPASSWORD_ERRROR.getMessage());
            return response;
        }
        // 验证用户是否验证通过
        Member member = members.get(0);
        if ("N".equals(member.getIsVerified())){
            response.setCode(UserRetCode.USER_ISVERFIED_ERROR.getCode());
            response.setMsg(UserRetCode.USER_ISVERFIED_ERROR.getMessage());
            return response;
        }
        // 验证密码
        String password = DigestUtils.md5DigestAsHex(userLoginRequest.getPassword().getBytes());
        if (!member.getPassword().equals(password)){
            response.setCode(UserRetCode.USERORPASSWORD_ERRROR.getCode());
            response.setMsg(UserRetCode.USERORPASSWORD_ERRROR.getMessage());
            return response;
        }
        // JWT生成Token
        HashMap<String, Object> map = new HashMap<>();
        map.put("uid",member.getId());
        map.put("file",member.getFile());
        map.put("userName",member.getUsername());
        String token = JwtTokenUtils.builder().msg(JSON.toJSONString(map)).build().creatJwtToken();
        UserLoginResponse userLoginResponse = userConverterMapper.converter(member);
        userLoginResponse.setToken(token);
        userLoginResponse.setCode(UserRetCode.SUCCESS.getCode());
        userLoginResponse.setMsg(UserRetCode.SUCCESS.getMessage());
        return userLoginResponse;
    }

    /**
     * lxc
     * @param userId
     * @return
     */
    @Override
    public String getUsernameByUserId(Long userId) {

        Member member = memberMapper.selectByPrimaryKey(userId);

        return member.getUsername();
    }

    @Override
    public UserRegisterResponse register(UserRegisterRequest registerRequest) {
        UserRegisterResponse response = new UserRegisterResponse();
        // 判空验证
        registerRequest.requestCheck();

        // 验证用户名是否重复
        volidUserNameRepeat(registerRequest);

        // 1.向用户表中插入一条记录
        Member member = new Member();
        member.setUsername(registerRequest.getUserName());
        member.setEmail(registerRequest.getEmail());
        // password 进行加密处理
        String userPassword = DigestUtils.md5DigestAsHex(registerRequest.getUserPwd().getBytes());
        member.setPassword(userPassword);
        member.setCreated(new Date());
        member.setUpdated(new Date());
        member.setIsVerified("N");
        member.setState(1);

        int effectRows = memberMapper.insert(member);
        if(effectRows != 1){
            response.setCode(UserRetCode.USER_REGISTER_FAILED.getCode());
            response.setMsg(UserRetCode.USER_REGISTER_FAILED.getMessage());
            return response;
        }
        // 2.向用户验证表中插入一条记录
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(member.getUsername());
        String key = member.getUsername() + member.getPassword() + UUID.randomUUID();
        String uuid = DigestUtils.md5DigestAsHex(key.getBytes());
        userVerify.setUuid(uuid);
        userVerify.setRegisterDate(new Date());
        userVerify.setIsExpire("N");
        userVerify.setIsVerify("N");
        int rows = userVerifyMapper.insert(userVerify);
        if(rows != 1){
            response.setCode(UserRetCode.USER_REGISTER_VERIFY_FAILED.getCode());
            response.setMsg(UserRetCode.USER_REGISTER_VERIFY_FAILED.getMessage());
            return response;
        }
        // 3.发送用户激活邮件
        // TODO 发送用户激活邮件，激活邮件应该是一个链接，有一个接口去处理我们的用户激活 消息中间件MQ
        sendEmail(uuid,registerRequest);

        // 打印日志
        log.info("用户注册成功，注册参数request:{}",JSON.toJSONString(registerRequest));
        response.setCode(UserRetCode.SUCCESS.getCode());
        response.setMsg(UserRetCode.SUCCESS.getMessage());
        return response;
    }
    // 发送激活邮件
    private void sendEmail(String uuid, UserRegisterRequest registerRequest) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("多来买新用户激活");
        message.setFrom("1205066911@qq.com");
        message.setTo(registerRequest.getEmail());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("http://localhost:8099/user/verify?uuid=").append(uuid).append("&username=").append(registerRequest.getUserName());
        message.setText(stringBuilder.toString());
        mailSender.send(message);
    }

    // 验证用户名是否重复
    private void volidUserNameRepeat(UserRegisterRequest registerRequest) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username",registerRequest.getUserName());
        List<Member> memberList = memberMapper.selectByExample(example);
        if(!CollectionUtils.isEmpty(memberList)){
            throw new ValidateException(UserRetCode.USERNAME_ALREADY_EXISTS.getCode(),UserRetCode.USERNAME_ALREADY_EXISTS.getMessage());
        }
    }
}
